<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <sticky :z-index="10" :class-name="'sub-navbar ' + postForm.status">
        <CommentDropdown v-model="postForm.commentDisabled" />
        <el-button
          v-loading="loading"
          style="margin-left: 10px;"
          type="success"
          @click="submitForm"
        >发布</el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">草稿</el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>标题</MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px" label="作者:" class="postInfo-container-item">
                    <el-select
                      v-model="postForm.userId"
                      :remote-method="getRemoteUserList"
                      filterable
                      default-first-option
                      remote
                      placeholder="Search user"
                    >
                      <el-option
                        v-for="(item, index) in userListOptions"
                        :key="item + index"
                        :label="item"
                        :value="index"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="60px" label="分類:" class="postInfo-container-item">
                    <el-select v-model="postForm.categoryId" placeholder="请选择文章分類">
                      <el-option
                        v-for="(item, index) in categoryList"
                        :key="index"
                        :label="item"
                        :value="index"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label-width="120px" label="发布时间:" class="postInfo-container-item">
                    <el-date-picker
                      v-model="formatCreateTime"
                      type="datetime"
                      format="yyyy-MM-dd HH:mm:ss"
                      value-format="timestamp"
                      placeholder="选择发布时间"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="主题:">
          <el-input
            v-model="postForm.contentShort"
            :rows="1"
            type="textarea"
            class="article-textarea"
            autosize
            placeholder="Please enter the content"
          />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
        </el-form-item>

        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="标签:">
          <vue-tags-input
            v-model="tag"
            :tags="tags"
            :autocomplete-items="autocompleteItems"
            @tags-changed="updateTags"
          />
        </el-form-item>

        <el-form-item prop="content" style="margin-bottom: 30px;">
          <markdown-editor
            ref="markdownEditor"
            v-model="postForm.content"
            :options="{hideModeSwitch : true, previewStyle : 'tab'}"
            height="900px"
          />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import MarkdownEditor from '@/components/MarkdownEditor'
import VueTagsInput from '@johmun/vue-tags-input'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
// import { validURL } from '@/utils/validate'
import { fetchArticle, createArticle, updateArticle } from '@/api/article'
import { searchUser, searchCategory, searchTags } from '@/api/remote-search'
import { CommentDropdown } from './Dropdown'

const defaultForm = {
  articleId: null,
  title: '', // 文章题目
  content: '', // 文章内容
  contentShort: '', // 文章摘要
  createTime: null, // 前台展示时间
  categoryId: null,
  tags: '',
  userId: '',
  commentDisabled: 0,
  status: 0
}

export default {
  name: 'ArticleDetail',
  components: {
    MDinput,
    Sticky,
    CommentDropdown,
    MarkdownEditor,
    VueTagsInput
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      categoryList: [],
      tag: '',
      autocompleteItems: [],
      rules: {
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        userId: [{ validator: validateRequire }]
      },
      tempRoute: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.contentShort.length
    },
    lang() {
      return this.$store.getters.language
    },
    formatCreateTime: {
      get() {
        return this.postForm.createTime * 1000
      },
      set(value) {
        this.postForm.createTime = value / 1000
      }
    },
    tags: {
      get() {
        const tags = this.postForm.tags ? this.postForm.tags.split(',') : []
        return tags.map(item => {
          return { text: item }
        })
      },
      set(value) {
        // 正常不会走到这个方法
        console.log(value)
      }
    }
  },
  watch: {
    tag: 'initItems'
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)

    // 初始化分類數據
    this.getCategoryList()
  },
  methods: {
    fetchData(id) {
      this.loading = true
      fetchArticle(id)
        .then(response => {
          const keys = Object.keys(response.data)
          keys.forEach(key => {
            if (this.postForm[key] !== undefined) {
              this.postForm[key] = response.data[key]
            }
          })
          this.postForm.userId = String(response.data.userId)
          // 初始化的时候设置userlist
          this.getRemoteUserList()
          this.loading = false
        })
        .catch(err => {
          console.log(err)
        })
    },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article'
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.postForm.id}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.postForm.id}`
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isEdit) {
            updateArticle(this.$route.params.id, this.postForm).then(() => {
              this.loading = false
              this.$router.push('/article/index')
            })
          } else {
            createArticle(this.postForm).then(() => {
              this.loading = false
              this.$router.push('/article/index')
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (
        this.postForm.content.length === 0 ||
        this.postForm.title.length === 0
      ) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.$message({
        message: '保存成功',
        type: 'success',
        showClose: true,
        duration: 1000
      })
      this.postForm.status = 1
    },
    getRemoteUserList(query) {
      searchUser(query).then(response => {
        if (response.data == null) return
        this.userListOptions = response.data
      })
    },
    getCategoryList() {
      searchCategory().then(res => {
        this.categoryList = res.data
      })
    },
    updateTags(newTags) {
      this.autocompleteItems = []
      this.postForm.tags = this.coverToString(newTags)
    },
    initItems() {
      if (this.tag.length < 2) return

      clearTimeout(this.debounce)
      this.debounce = setTimeout(() => {
        searchTags(this.tag)
          .then(response => {
            const items = []
            for (const i in response.data) {
              items.push({ text: response.data[i] })
            }
            this.autocompleteItems = items
          })
          .catch(() => console.warn('Oh. Something went wrong'))
      }, 600)
    },
    coverToString(tagsArray) {
      const tags = tagsArray.map(item => {
        return item.text
      })
      return tags.join(',')
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea /deep/ {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
